/* eslint-disable no-undef */
import fs from 'node:fs'
import log4js from 'log4js'
const root_path = process.cwd()

const logConfig = {
    appenders: {
        out: { type: 'stdout' },
        errFile: {
            type: 'dateFile',
            filename: `${root_path}/runtime/logs/err/err`,
            alwaysIncludePattern: true,
            pattern: 'yyMMdd.log'
        },
        err: {
            type: 'logLevelFilter',
            level: 'error',
            appender: 'errFile'
        },
        logFile: {
            type: 'dateFile',
            filename: `${root_path}/runtime/logs/log/log`,
            alwaysIncludePattern: true,
            pattern: 'yyMMdd.log',
        },
        log: {
            type: 'logLevelFilter',
            level: 'info',
            appender: 'logFile'
        },
    },
    // levelOpt: 'ALL TRACE DEBUG INFO WARN ERROR FATAL OFF',
    categories: {
        // 缺省输出
        default: {
            appenders: ['out', 'err', 'log'],
            level: 'all'
        }
    }
}

/**
 * 创建日志目录
 */
const makePath = () => {
    try {
        if (!fs.existsSync(`${root_path}/runtime/logs/`))
            fs.mkdirSync(`${root_path}/runtime/logs/`)

        if (!fs.existsSync(`${root_path}/runtime/logs//err`))
            fs.mkdirSync(`${root_path}/runtime/logs//err`)

        if (!fs.existsSync(`${root_path}/runtime/logs//log`))
            fs.mkdirSync(`${root_path}/runtime/logs//log`)
    } catch (e) {
        console.error('Create log directory: ' + root_path + ' exp: ' + e.message)
    }
}

makePath()

// 日志配置加载，reloadSecs（每隔 300秒检查设置变更）
log4js.configure(logConfig/* , { reloadSecs: 300 } */)

export default log4js